from contextlib import closing
from os import makedirs
from os.path import exists

import requests
imagePath = 'image'
pre_ = "photos_z5_"
small_pre_ = "small_photos_z5_"

def download(photo_url, dir_name, filename):
    jpg_filename = dir_name + '/' + filename
    if not exists(jpg_filename):
        with closing(requests.get(url=photo_url, stream=True, timeout=90)) as r:
            with open(jpg_filename, 'ab+') as f:
                for chunk in r.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
                        f.flush()


def post_yinghuo():
    # last_id=0&system_version=6.0.1&lan=en&source=android&token=6ef3a7e96128db97d3e67c6adeac62f9&uuid=1d4e879a-6fbc-3049-78e9-2189b72c6b64&version_code=2019120900&timestamp=1578637025&device_code=&device_name=SAMSUNG-SM-G925A&udid=ee2f71475b1647ec&page=1&channel=c1098&nonce=1578637025966E0

    feature = 1
    page = 1

    if not exists(imagePath):
        makedirs(imagePath)
    while True:
        try:
            headers = {'content-type': 'application/x-www-form-urlencoded', 'accept-encoding': 'gzip',
                       'user-agent': 'okhttp/3.12.0'}
            payload = 'system_version=6.0.1&lan=en&source=android&token=993347b811fbcac7df45779cd5dfbbf6&uuid=1d4e879a-6fbc-3049-78e9-2189b72c6b64&version_code=2020092502&timestamp=1603869976&device_code=&device_name=SAMSUNG-SM-G925A&uid=&udid=ee2f71475b1647ec&page=' + str(page) + '&channel=c1098&nonce=16038699769661B'
            r = requests.post("https://api.hyhuo.com/home/img_recommend", headers=headers, data=payload)
            print(page)
            # print(r.json())
            page = page + 1
            json_data = r.json()
            data = json_data['data']
            if data:
                data_list = data['data_list']
                if data_list:
                    for item in data_list:
                        try:

                            thumb_img = item['thumb_img']
                            small_img = thumb_img
                            try:
                                thumb_img = item['image_group'][0]['img_url']
                            except:
                                pass
                            print(thumb_img)
                            suffix = '.jpg'
                            if thumb_img.__contains__('webp'):
                                suffix = '.webp'
                            elif thumb_img.__contains__('png'):
                                suffix = '.png'
                            download(thumb_img, imagePath, pre_ + str(feature) + suffix)
                            download(small_img, imagePath, small_pre_ + str(feature) + suffix)
                            print("已保存图片: " + pre_ + str(feature) + suffix)
                            feature = feature + 1
                        except:
                            pass
                else:
                    print("在第" + str(page) + "页因各种原因退出， feature 已经到达:" + str(feature))
                    break
            else:
                print("在第" + str(page) + "页因各种原因退出， feature 已经到达:" + str(feature))
                break
        except:
            print("在第" + str(page) + "页因各种原因退出， feature 已经到达:" + str(feature))
            pass


if __name__ == '__main__':
    post_yinghuo()
